#!/bin/bash
#################################################
# filename: ssh_port.sh
# 功能: 本机端口通过跳板机转发到远程端口
# 执行方法：
# ssh_port start 8080 10.10.2.2 80
# ssh_port stop 8080
# ssh_port status 8080
#################################################

check(){
    # 验证参数是否为空
    if [[ ${#@} < 1 ]]; then
        echo "请输入参数！"
        echo "开启端口转发：ssh_port start 8080 10.10.2.2 80"
        echo "关闭端口转发：ssh_port stop 8080"
        echo "查看端口状态：ssh_port status 8080"
        exit 1
    fi
}

check $@

# 工作目录
WORKDIR="/home/$(whoami)/workdir"

# 操作类型
operation="$1"

# 本地端口
local_port="$2"

# 远程 IP 地址
remote_ip="$3"

# 远程端口
remote_port="$4"

# SSH 控制套接字文件
sock_file="$WORKDIR/$local_port.sock"

# 跳板机
jump_name=jump-machine

start(){
    echo "start port begin........"
    pid=$(netstat -tunpl | grep "127.0.0.1:$local_port" | grep ssh | awk '{print $7}' | cut -d'/' -f1 | sort | uniq)
    if [ -z "$pid" ]; then
        # 建立连接
        ssh -nNT -S "$sock_file" -L 127.0.0.1:$local_port:$remote_ip:$remote_port $jump_name
        echo "ssh -nNT -S ${sock_file} -L 127.0.0.1:${local_port}:${remote_ip}:${remote_port} ${jump_name}"
        echo "start port success!"
        sleep 1
    else
        echo "port is running."
    fi
}

stop(){
    echo "stop port begin........"
    pid=$(netstat -tunpl | grep "127.0.0.1:$local_port" | grep ssh | awk '{print $7}' | cut -d'/' -f1 | sort | uniq)
    if [ -z "$pid" ]; then
        echo "No port running."
    else
        echo "The port (${pid}) is running..."
        ssh -S $sock_file -O exit $jump_name
        echo "ssh -S $sock_file -O exit $jump_name"
        echo "stop port (${pid}) success!"
    fi
}

status(){
    echo "check status port begin........"
    pid=$(netstat -tunpl | grep "127.0.0.1:$local_port" | grep ssh | awk '{print $7}' | cut -d'/' -f1 | sort | uniq)
    if [ -z "$pid" ]; then
        echo "No port running."
    else
        echo "The port (${pid}) is running..."
        netstat -tunpl | grep "127.0.0.1:$local_port"
    fi
}

if [ -n "$operation" ]; then
    # 判断操作类型
    if [[ "$operation" == "start" ]]; then
        # 建立连接
        start
    elif [[ "$operation" == "stop" ]]; then
        # 关闭连接
        stop
    elif [[ "$operation" == "status" ]]; then
        # 查看状态
        status
    else
        check
        exit 1
    fi
fi

